
package cn.nubia.admin.application.controller;

import cn.nubia.admin.application.bean.Soft;
import cn.nubia.admin.application.bean.SoftItem;
import cn.nubia.admin.application.bean.SoftUSoftItem;
import cn.nubia.admin.application.bean.SoftVO;
import cn.nubia.admin.application.query.SoftItemQuery;
import cn.nubia.admin.application.query.SoftQuery;
import cn.nubia.admin.application.service.*;
import cn.nubia.admin.sysconfig.bean.DictField;
import cn.nubia.admin.sysconfig.service.CategoryService;
import cn.nubia.admin.common.mybatis.bean.Paged;
import cn.nubia.admin.common.springmvc.Response;
import cn.nubia.admin.common.springmvc.WebContext;
import cn.nubia.admin.sysconfig.service.DictFieldItemService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by justin on 15/6/30.
 */
@Controller
@RequestMapping(value = "/admin/soft/")
public class SoftController {

    public static final String PARENT_UPLOAD = "appUploadFlag";
    public static final String PARENT_APPLICATION = "ApplicationFlag";

    @Autowired
    SoftService softService;
    @Autowired
    ScreenshotService screenshotService;
    @Autowired
    SoftItemService softItemService;
    @Autowired
    TerminalService terminalService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DictFieldItemService dictFieldItemService;
    @Autowired
    FirewareService firewareService;

    /**
     * 星级**
     */
    private static final Map<String, String> starEnums = new TreeMap<>();

    static {
        starEnums.put("0.5", "0.5");
        starEnums.put("1", "1");
        starEnums.put("1.5", "1.5");
        starEnums.put("2", "2");
        starEnums.put("2.5", "2.5");
        starEnums.put("3", "3");
        starEnums.put("3.5", "3.5");
        starEnums.put("4", "4");
        starEnums.put("4.5", "4.5");
        starEnums.put("5", "5");
    }

    /**
     * 展示新增APK的界面
     *
     * @return
     */
    @RequiresPermissions(value = "soft:appupload:addApk")
    @RequestMapping(value = "addApk", method = RequestMethod.GET)
    public ModelAndView addApk(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/app/addApk");
        setCategoryList(0, null, modelAndView);
        addEnums(modelAndView);
        return modelAndView;
    }


    /**
     * 查看
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "viewSoftItem", method = RequestMethod.GET)
    public ModelAndView viewSoftItem(HttpServletRequest request, Integer id) {
        ModelAndView modelAndView = new ModelAndView("/app/editSoftItem");
        getSoftItemContent(request, id, modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("readonly", true);
        return modelAndView;
    }




    @RequestMapping(value = "editSoftItem", method = RequestMethod.GET)
    public ModelAndView editSoftItem(HttpServletRequest request, Integer id) {
        ModelAndView modelAndView = new ModelAndView("/app/editSoftItem");
        getSoftItemContent(request, id, modelAndView);
        addEnums(modelAndView);
        return modelAndView;
    }

    @RequestMapping(value = "editSoft", method = RequestMethod.GET)
    public ModelAndView editSoft(HttpServletRequest request, Integer id) {
        ModelAndView modelAndView = new ModelAndView("/app/editSoft");
        getSoftContent(request, id, modelAndView);
        addEnums(modelAndView);
        return modelAndView;
    }


    private ModelAndView getSoftContent(HttpServletRequest request, Integer id, ModelAndView modelAndView) {
        SoftVO vo = softService.getSoftId(id);
        this.setCategoryList(vo.getCategoryId(), vo.getCategoryId2(), modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("vo", vo);
        return modelAndView;
    }

    private ModelAndView getSoftItemContent(HttpServletRequest request, Integer id, ModelAndView modelAndView) {
        SoftVO vo = softService.getSoftBySoftItemId(id);
        this.setCategoryList(vo.getCategoryId(), vo.getCategoryId2(), modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("vo", vo);
        return modelAndView;
    }

    /**
     * 草稿列表
     *
     * @return
     */
    @RequiresPermissions(value = "soft:appupload:listDraft")
    @RequestMapping(value = "listDraft", method = RequestMethod.GET)
    public ModelAndView listDraft(SoftItemQuery softQuery) {
        ModelAndView modelAndView = new ModelAndView("/app/softItemList");
        softQuery.setState(1);
        Paged<SoftUSoftItem> softItems = softItemService.findPagedList(softQuery);
        this.setCategoryList(softQuery.getCategoryId(), softQuery.getCategoryId2(), modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("state", softQuery.getState());
        modelAndView.addObject("state", softQuery.getState());
        modelAndView.addObject("fromType", "listDraft");
        modelAndView.addObject("parentType", PARENT_UPLOAD);
        modelAndView.addObject("softItems", softItems);
        modelAndView.addObject("query", softQuery);
        return modelAndView;
    }

    /**
     * 待审列表
     *
     * @return
     */
    @RequiresPermissions(value = "soft:appupload:listWaitCheck")
    @RequestMapping(value = "listWaitCheck", method = RequestMethod.GET)
    public ModelAndView listWaitCheck(SoftItemQuery softQuery) {
        ModelAndView modelAndView = new ModelAndView("/app/softItemList");
        softQuery.setState(0);
        Paged<SoftUSoftItem> softItems = softItemService.findPagedList(softQuery);
        setCategoryList(softQuery.getCategoryId(), softQuery.getCategoryId2(), modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("state", softQuery.getState());
        modelAndView.addObject("softItems", softItems);
        modelAndView.addObject("fromType", "listWaitCheck");
        modelAndView.addObject("parentType", PARENT_UPLOAD);
        modelAndView.addObject("query", softQuery);
        return modelAndView;
    }

    /**
     * 软件管理
     *
     * @return
     */
    @RequiresPermissions(value = "soft:app:listSoft")
    @RequestMapping(value = "listSoft", method = RequestMethod.GET)
    public ModelAndView listWaitCheck(SoftQuery softQuery) {
        ModelAndView modelAndView = new ModelAndView("/app/softList");
        Paged<Soft> softItems = softService.findList(softQuery);
        setCategoryList(softQuery.getCategoryId(), softQuery.getCategoryId2(), modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("softs", softItems);
        modelAndView.addObject("fromType", "listSoft");
        modelAndView.addObject("parentType", PARENT_APPLICATION);

        modelAndView.addObject("query", softQuery);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = "listSoftsSync")
    public Response<Paged<Soft>> listSoftsSync(SoftQuery softQuery){
        Paged<Soft> softs = softService.findList(softQuery);
        return Response.getSuccessResponse(softs);
    }



    @ResponseBody
    @RequestMapping(value = "searchSoft")
    public List<Soft> searchSoft(SoftQuery softQuery) {
        List<Soft> softs = softService.findSoftList(softQuery);
        return softs;
    }

    /**
     * 软件版本列表
     *
     * @return
     */
    @RequiresPermissions(value = "soft:app:listSoftItems")
    @RequestMapping(value = "listSoftItems", method = RequestMethod.GET)
    public ModelAndView listSoftItems(SoftItemQuery softQuery) {
        ModelAndView modelAndView = new ModelAndView("/app/softItemList");
        Paged<SoftUSoftItem> softItems = softItemService.findPagedList(softQuery);
        setCategoryList(softQuery.getCategoryId(), softQuery.getCategoryId2(), modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("softItems", softItems);
        modelAndView.addObject("fromType", "listSoftItems");
        modelAndView.addObject("parentType", PARENT_APPLICATION);
        modelAndView.addObject("query", softQuery);
        return modelAndView;
    }

    /**
     * 窗口软件版本列表
     *
     * @return
     */
    @RequestMapping(value = "listSoftItemsForWindow", method = RequestMethod.GET)
    public ModelAndView listSoftItemsForWindow(SoftItemQuery softQuery) {
        ModelAndView modelAndView = new ModelAndView("/app/softItemListForWindow");
        List<SoftUSoftItem> softItems = softItemService.findList(softQuery);
        modelAndView.addObject("softItems", softItems);
        return modelAndView;
    }


    /**
     * 我的审核列表
     *
     * @return
     */
    @RequiresPermissions(value = "soft:appupload:myCheckedList")
    @RequestMapping(value = "myCheckedList", method = RequestMethod.GET)
    public ModelAndView myCheckedList(SoftItemQuery softQuery) {
        ModelAndView modelAndView = new ModelAndView("/app/softItemList");
        softQuery.setCheckAdminId(WebContext.getCachedUser().getId());
        Paged<SoftUSoftItem> softItems = softItemService.findPagedList(softQuery);
        setCategoryList(softQuery.getCategoryId(), softQuery.getCategoryId2(), modelAndView);
        addEnums(modelAndView);
        modelAndView.addObject("state", softQuery.getState());
        modelAndView.addObject("checkAdminId", softQuery.getCheckAdminId());
        modelAndView.addObject("softItems", softItems);
        modelAndView.addObject("fromType", "myCheckedList");
        modelAndView.addObject("parentType", PARENT_UPLOAD);

        modelAndView.addObject("query", softQuery);
        return modelAndView;
    }


    /**
     * 根据softItem信息增加
     * soft（如果未入库）
     * softItem
     * 需要判定最新版本
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public Response<Boolean> save(@Valid SoftVO vo, BindingResult result) {
        if (result.hasErrors()) return Response.getFailedResponse(result.getAllErrors().get(0).getDefaultMessage());

        if(StringUtils.isEmpty(vo.getUpdateDescription()))return Response.getFailedResponse("请输入版本更新介绍！");
        if(vo.getUpdateDescription().length()>1000)return Response.getFailedResponse("请输入少于1000字版本更新介绍！");

        softService.processAddSoftItem(vo);
        return Response.getSuccessResponse(true);
    }

    @ResponseBody
    @RequestMapping(value = "saveSoft")
    public Response<Boolean> saveSoft(Soft soft){
        softService.saveSoft(soft);
        return Response.getSuccessResponse(true);
    }


    @ResponseBody
    @RequestMapping(value = "delSoftItem")
    public boolean delSoftItem(Integer id) {
        return softItemService.delSoftItem(id);
    }


    @ResponseBody
    @RequestMapping(value = "upSoftItem")
    public boolean upSoftItem(Integer id) {
        return softItemService.changeState(id, SoftItem.STATE_CHECKED);
    }

    @ResponseBody
    @RequestMapping(value = "downSoftItem")
    public boolean downSoftItem(Integer id) {
        return softItemService.changeState(id, SoftItem.STATE_DOWN);
    }

    @ResponseBody
    @RequestMapping(value = "hiddenSoftItem")
    public boolean hiddenSoftItem(Integer id) {
        return softItemService.changeState(id, SoftItem.STATE_HIDDEN);
    }

    @ResponseBody
    @RequestMapping(value = "showSoftItem")
    public boolean showSoftItem(Integer id) {
        return softItemService.changeState(id, SoftItem.STATE_CHECKED);
    }

    @ResponseBody
    @RequestMapping(value = "delSoft")
    public boolean delSoft(Integer id) {
        return softService.delSoft(id);
    }


    @ResponseBody
    @RequestMapping(value = "checkNoItem")
    public  boolean checkNoItem(Integer id,String checkReason){
        return softItemService.checkNoItem(id,checkReason);
    }


    /**
     * *
     * 删除指定的screenshot。只在数据库假删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delScreenshot", method = RequestMethod.GET)
    public boolean delScreenshot(Integer id) {
        screenshotService.disableScreenshot(id);
        return true;
    }

    private void addEnums(ModelAndView modelAndView) {
        modelAndView.addObject("starEnums", starEnums);
        modelAndView.addObject("terminals", dictFieldItemService.listItemsByDictName(DictField.DICTFIELDITEM_DEVICETYPE));//设备
        modelAndView.addObject("languages", dictFieldItemService.listItemsByDictName(DictField.DICTFIELDITEM_LANGUAGE));//语言
        modelAndView.addObject("softItemStatus", SoftItem.softItemStatus);
        modelAndView.addObject("softSrcs", dictFieldItemService.listItemsByDictName(DictField.DICTFIELDITEM_SOFT_RESOURCE));//软件来源
        modelAndView.addObject("safeStates", dictFieldItemService.listItemsByDictName(DictField.DICTFIELDITEM_SOFT_ITEMS_SAFE));//安全状态
    }

    private void setCategoryList(Integer firtCategoryId, Integer secCategoryId, ModelAndView modelAndView) {
        modelAndView.addObject("firstCatagories", categoryService.getSubCategoryList(0));
        if (firtCategoryId != null && firtCategoryId > 0) {
            modelAndView.addObject("secondCatagories", categoryService.getSubCategoryList(firtCategoryId));
            if (secCategoryId != null && secCategoryId > 0) {
                modelAndView.addObject("thirdCatagories", categoryService.getSubCategoryList(secCategoryId));
            }
        }
    }



}
